package cosplay.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import cosplay.Beans.Votes;
import cosplay.DAO.UserDAOImpl;
import cosplay.DAO.VoteDAOImpl;
import cosplay.Services.CommonServices;

@Controller
public class VoteController extends MultiActionController{
	@Autowired
	UserDAOImpl userdao;
	@Autowired
	VoteDAOImpl votedao;
	
	@RequestMapping(value="/addvote.htm")
	protected ModelAndView handelActAdd(HttpServletRequest req, HttpServletResponse res)throws Exception
	{
		Votes vote=getVoteFromRequest(req);
		if(votedao.add(vote)>0)
		{
			res.setIntHeader("sucess", 1);
		}
		else
		{
			res.setIntHeader("sucess", 0);
		}
		return null;
	}
	
	@RequestMapping(value="/delvote.htm")
	protected ModelAndView handelActDel(HttpServletRequest req, HttpServletResponse res)throws Exception
	{
		Votes vote=getVoteFromRequest(req);
		if(votedao.delete(vote.getUserID(), vote.getResultID()))
		{
			res.setIntHeader("sucess", 1);
		}
		else
		{
			res.setIntHeader("sucess", 0);
		}
		return null;
	}
	
	private Votes getVoteFromRequest(HttpServletRequest req)
	{
		if (req.getParameterMap().containsKey("rid"))
		{
			Votes vote=new Votes();
			//vote.setId(CommonServices.getIDFromRequest(req, "voteid"));
			vote.setPhotoID(CommonServices.getIDFromRequest(req, "photoid"));
			vote.setUserID(userdao.getByName(CommonServices.getLoggedUsername(req)).getId());
			vote.setVoteIP(req.getRemoteAddr());
			return vote;
		}
		else
		{
			return null;
		}
	}

}
